const { pool } = require("../../db");

exports.getAllComments = async (page, limit, type, offset) => {
  const baseQuery =
    type == 0
      ? "SELECT food.id as id,food.`name` as name FROM food LIMIT ? OFFSET ?"
      : "SELECT travel.id as id , travel.`name` as name FROM travel LIMIT ? OFFSET ?";

  const countQuery =
    type == 0
      ? "SELECT COUNT(*) as count FROM food"
      : "SELECT COUNT(*) as count FROM travel";
  const commentQuery =
    type == 0
      ? "SELECT f.id as parentId, c.id as comment_id , c.user_id ,c.food_id,c.content,c.rating as comment_rating ,c.media_urls,c.is_online,u.id as u_id,u.nickname from food f LEFT JOIN `comment` c ON f.id=c.food_id LEFT JOIN `user` u ON c.user_id=u.user_id WHERE f.id = ?"
      : "SELECT t.id as parentId, c.id as comment_id , c.user_id ,c.travel_id,c.content,c.rating as comment_rating ,c.media_urls,c.is_online,u.id as u_id,u.nickname from travel t LEFT JOIN `comment` c ON t.id=c.travel_id LEFT JOIN `user` u ON c.user_id=u.user_id WHERE t.id = ?";

  try {
    // 查询总数
    const [countResult] = await pool.query(countQuery);
    const totalCount = countResult[0].count;

    // 查询基础数据
    const [dataResult] = await pool.query(baseQuery, [limit, offset]);

    // 处理数据
    const precessedData = await Promise.all(
      dataResult.map(async (row) => {
        const { id, name } = row;
        // 查询评论数据
        const [commentResult] = await pool.query(commentQuery, [id]);
        // 处理评论数据
        let commentData = [];
        if (commentResult[0].comment_id) {
          commentData = commentResult.map((item) => {
            const { parentId, ...comment } = item;
            return comment;
          });
        }
        return {
          id,
          name,
          comments: commentData,
        };
      })
    );
    return { code: 200, data: precessedData, total: totalCount };
  } catch (error) {
    return { code: 500, msg: "服务器错误" };
  }
};

exports.updateIsOnline = async (id, isOnline) => {
  const query = `UPDATE comment SET is_online = ${isOnline} WHERE id = ${id}`;
  try {
    await pool.query(query);
    return { code: 200, message: "更新成功" };
  } catch (error) {
    return { code: 500, message: "更新失败" };
  }
};
